<template>
    <div>
        <!-- :http-request="uploadImg"绑定上传文件的方法 -->
        <el-upload
        class="avatar-uploader"
            action
            :http-request="uploadImg"
            list-type="picture-card"
            :limit="1"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <!-- <i class="el-icon-plus" ></i> -->
            <!-- <el-button type="primary" icon="el-icon-edit" circle></el-button> -->
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog >

    </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  // 刷新页面函数
  inject: ['reload'],
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  computed: {
    ...mapState(
      {
        userInfo: state => state.user.userInfo,
        backUrl: state => state.user.backUrl
      }
    ),
    imageUrl: function () {
      return this.backUrl + this.userInfo.profilePhoto
    }
  },
  methods: {
    // 上传头像
    async uploadImg (fileObj) {
      const formData = new FormData()
      formData.set('file', fileObj.file)
      const { data: res } = await this.$http.post('/user/updateHead', formData, { headers: { 'Content-type': 'multipart/form-data' } })
      console.log(res)

      //  上传新头像后，不显示旧的图片
      this.imageUrl = ''
      // 上传成功刷新页面
      // window.location.reload()
    },

    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }

  }
}
</script>

<style lang="less" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 146.4px;
    height: 146.4px;
    line-height: 146.4px;
    text-align: center;
  }
  .avatar {
    width: 146.4px;
    height: 146.4px;
    display: block;
  }
</style>
